import os
import shutil
import stat
import sys
from datetime import datetime

def remove_readonly(func, path, _):
    """清除只读属性后重试删除"""
    os.chmod(path, stat.S_IWRITE)
    func(path)

def delete_Objects_folders():
    """
    安全删除当前目录下所有子文件夹中的 Objects 文件夹
    """
    base_dir = os.getcwd()  # 获取当前工作目录
    deleted = []
    failures = []
    scan_count = 0

    print(f"[System] 工作目录：{os.path.abspath(base_dir)}")
    print("[System] 开始扫描目标文件夹...\n")

    # 遍历当前目录的第一级子目录
    for item in os.listdir(base_dir):
        item_path = os.path.join(base_dir, item)
        
        # 仅处理普通目录且非隐藏文件夹
        if os.path.isdir(item_path) and not item.startswith('.'):
            target_path = os.path.join(item_path, 'Objects')
            scan_count += 1
            
            if os.path.exists(target_path):
                print(f"✔️ 发现目标：{target_path}")
                try:
                    # 强制删除只读文件
                    shutil.rmtree(
                        target_path,
                        onerror=remove_readonly,
                        ignore_errors=False
                    )
                    deleted.append(target_path)
                    print("   → 删除成功")
                except Exception as e:
                    failures.append((target_path, str(e)))
                    print(f"   → 删除失败: {str(e)}")

    # 生成操作报告
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    report = (
        "\n=== 操作报告 ===\n"
        f"时间: {timestamp}\n"
        f"扫描目录数: {scan_count}\n"
        f"成功删除: {len(deleted)}\n"
        f"失败次数: {len(failures)}\n"
    )

    # 写入日志文件
    with open("deletion_log.txt", "a", encoding="utf-8") as f:
        f.write(report)
        if deleted:
            f.write("\n[删除成功列表]\n")
            f.write("\n".join(deleted))
        if failures:
            f.write("\n\n[删除失败列表]\n")
            f.write("\n".join(f"{p} ({e})" for p, e in failures))

    # 控制台输出
    print(report)
    print("详细日志已保存至 deletion_log.txt")

if __name__ == "__main__":
    # 红色警告提示
    print("\033[91m")
    print("⚠️ 高危操作警告 ⚠️".center(50))
    print("\033[0m")
    print("本脚本将执行以下操作：")
    print("1. 删除当前目录下所有直接子文件夹中的 Objects 文件夹")
    print("2. 永久性删除操作不可撤销")
    print("3. 自动跳过隐藏文件夹（以 . 开头）\n")

    # 双重确认机制
    confirm = input("请输入 'CONFIRM' 继续: ").strip()
    if confirm != "CONFIRM":
        print("\n操作已取消")
        sys.exit(0)

    # 执行删除操作
    try:
        delete_Objects_folders()
    except KeyboardInterrupt:
        print("\n\n操作被用户中断")
        sys.exit(1)
